const Device = require('../models/Device');
const { successResponse, errorResponse } = require('../utils/responses');

/**
 * @desc    获取用户设备列表
 * @route   GET /api/devices
 * @access  私有
 */
const getUserDevices = async (req, res) => {
  try {
    const { type } = req.query;
    const devices = await Device.getUserDevices(req.user.id, type);
    
    return successResponse(res, 200, '获取设备列表成功', {
      count: devices.length,
      devices
    });
  } catch (error) {
    console.error('获取设备列表失败:', error);
    return errorResponse(res, 500, '服务器错误', [error.message]);
  }
};

/**
 * @desc    获取单个设备详情
 * @route   GET /api/devices/:id
 * @access  私有
 */
const getDeviceById = async (req, res) => {
  try {
    const device = await Device.findOne({ 
      _id: req.params.id,
      user: req.user.id
    });

    if (!device) {
      return errorResponse(res, 404, '设备不存在');
    }

    return successResponse(res, 200, '获取设备详情成功', device);
  } catch (error) {
    console.error('获取设备详情失败:', error);
    return errorResponse(res, 500, '服务器错误', [error.message]);
  }
};

/**
 * @desc    添加设备
 * @route   POST /api/devices
 * @access  私有
 */
const addDevice = async (req, res) => {
  try {
    const { deviceId, name, type, model, manufacturer, firmware } = req.body;

    // 验证必要字段
    if (!deviceId || !name || !type) {
      return errorResponse(res, 400, '缺少必要参数', ['请提供设备ID、名称和类型']);
    }

    // 检查设备类型是否有效
    const validTypes = ['glucose', 'bloodPressure', 'weight'];
    if (!validTypes.includes(type)) {
      return errorResponse(res, 400, '无效的设备类型', [`设备类型必须是: ${validTypes.join(', ')}`]);
    }

    // 检查设备是否已存在
    const existingDevice = await Device.findOne({ 
      deviceId, 
      user: req.user.id,
      isActive: true
    });

    if (existingDevice) {
      return errorResponse(res, 400, '设备已存在', ['此设备已经添加到您的账户']);
    }

    // 创建新设备
    const device = new Device({
      user: req.user.id,
      deviceId,
      name,
      type,
      model: model || '',
      manufacturer: manufacturer || '',
      firmware: firmware || '',
      connectionStatus: 'connected',
      lastSyncDate: new Date()
    });

    await device.save();

    return successResponse(res, 201, '设备添加成功', device);
  } catch (error) {
    console.error('添加设备失败:', error);
    return errorResponse(res, 500, '服务器错误', [error.message]);
  }
};

/**
 * @desc    更新设备信息
 * @route   PUT /api/devices/:id
 * @access  私有
 */
const updateDevice = async (req, res) => {
  try {
    // 查找设备
    let device = await Device.findOne({ 
      _id: req.params.id,
      user: req.user.id
    });

    if (!device) {
      return errorResponse(res, 404, '设备不存在');
    }

    const { customName, connectionStatus, model, manufacturer, firmware } = req.body;

    // 只允许更新特定字段
    if (customName !== undefined) device.customName = customName;
    if (connectionStatus !== undefined) device.connectionStatus = connectionStatus;
    if (model !== undefined) device.model = model;
    if (manufacturer !== undefined) device.manufacturer = manufacturer;
    if (firmware !== undefined) device.firmware = firmware;

    // 保存更新
    await device.save();

    return successResponse(res, 200, '设备信息更新成功', device);
  } catch (error) {
    console.error('更新设备信息失败:', error);
    return errorResponse(res, 500, '服务器错误', [error.message]);
  }
};

/**
 * @desc    删除设备
 * @route   DELETE /api/devices/:id
 * @access  私有
 */
const deleteDevice = async (req, res) => {
  try {
    // 查找设备
    const device = await Device.findOne({ 
      _id: req.params.id,
      user: req.user.id
    });

    if (!device) {
      return errorResponse(res, 404, '设备不存在');
    }

    // 软删除 - 将设备标记为非活动状态
    device.isActive = false;
    await device.save();

    return successResponse(res, 200, '设备删除成功', { id: req.params.id });
  } catch (error) {
    console.error('删除设备失败:', error);
    return errorResponse(res, 500, '服务器错误', [error.message]);
  }
};

/**
 * @desc    更新设备同步时间
 * @route   PUT /api/devices/:id/sync
 * @access  私有
 */
const updateDeviceSync = async (req, res) => {
  try {
    // 查找设备
    const device = await Device.findOne({ 
      _id: req.params.id,
      user: req.user.id
    });

    if (!device) {
      return errorResponse(res, 404, '设备不存在');
    }

    // 更新同步时间
    device.lastSyncDate = new Date();
    await device.save();

    return successResponse(res, 200, '设备同步时间更新成功', {
      deviceId: device._id,
      lastSyncDate: device.lastSyncDate
    });
  } catch (error) {
    console.error('更新设备同步时间失败:', error);
    return errorResponse(res, 500, '服务器错误', [error.message]);
  }
};

module.exports = {
  getUserDevices,
  getDeviceById,
  addDevice,
  updateDevice,
  deleteDevice,
  updateDeviceSync
}; 